﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QWeiBoN.ViewModule;
using QWeiBoN.Objects;
using TencentWeiboSDK.Model;
using System.Windows.Media.Imaging;
using System.IO;
using QWeiBoN.Util;
using QWeiBo.ViewModule;

namespace QWeiBoN.UserControler
{
    public partial class WeiboDetailPage : PhoneApplicationPage
    {

        #region 私有属性

        /// <summary>
        /// 微博ID
        /// </summary>
        private string weiboId;

        /// <summary>
        /// 评论对应的原始文本
        /// </summary>
        private string fatherText;

        /// <summary>
        /// 父微博发布人名称
        /// </summary>
        private string fatherName;

        /// <summary>
        /// 是否显示选择表情或者话题或者提及
        /// </summary>
        private bool isShowPop { get; set; }

        /// <summary>
        /// 微博评论列表服务
        /// </summary>
        private WeiboCommentsModel wcModel = new WeiboCommentsModel();

        /// <summary>
        /// 拉取数据类型
        /// </summary>
        private enum EPollType
        {
            /// <summary>
            /// 默认，结果绑定到控件
            /// </summary>
            Default,
            /// <summary>
            /// 下一页，结果追加到末尾
            /// </summary>
            NextPage,
            /// <summary>
            /// 最新，结果插到开头
            /// </summary>
            Lastest
        }

        /// <summary>
        /// 加载数据的类型
        /// </summary>
        private EPollType pollType { get; set; }

        /// <summary>
        /// 是否正在拉取数据
        /// </summary>
        private bool isPolling { get; set; }

        /// <summary>
        /// 最后一条评论的时间戳
        /// </summary>
        private long lastTimestamp { get; set; }
        /// <summary>
        /// 第一条评论的时间戳
        /// </summary>
        private long firstTimestamp { get; set; }

        /// <summary>
        /// 最后一次刷新的时间
        /// </summary>
        private DateTime lastPollTime { get; set; }

        /// <summary>
        /// 手势是否是垂直拖拽
        /// </summary>
        private bool isVerticalDrag { get; set; }

        #endregion

        public WeiboDetailPage()
        {
            InitializeComponent();
        }

        #region 导航处理

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // 清理原始内容
            DetailUserNick.Text = string.Empty;
            DetailUserName.Text = string.Empty;
            DetailUserVip.Visibility = Visibility.Collapsed;
            BitmapImage source = new BitmapImage();
            source.UriSource = new Uri("/Resources/noHead.png", UriKind.Relative);
            DetailUserHead.Source = source;

            if (NavigationContext.QueryString.ContainsKey(AppSetting.CommentsListTypeKey))
            {
                weiboId = NavigationContext.QueryString[AppSetting.CommentsListTypeKey];
                
                if (!string.IsNullOrWhiteSpace(weiboId))
                {
                    DetailCommentsList.ItemsSource = null;
                    DetailCommentsList.UpdateLayout();
                    DetailItemGrid.DataContext = null;
                    DetailItemGrid.UpdateLayout();
                    DetailUserInfo.Tag = string.Empty;
                    //RefreshCommentsList(PageFlag.First, 0);
                    RefreshWeiboDetail();
                }
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        #endregion

        #region 数据绑定

        /// <summary>
        /// 用于得到微博详细信息
        /// </summary>
        private void RefreshWeiboDetail()
        {
            DetailProgressBar.IsIndeterminate = true;
            wcModel.getWeiboDetail(weiboId, (callback) =>
            {

                DetailItemGrid.DataContext = callback.Data;

                // 设置进度条
                Dispatcher.BeginInvoke(() =>
                {
                    DetailUserNick.Text = callback.Data.Nick;
                    DetailUserName.Text = callback.Data.Name;
                    if (null != callback.Data.Head)
                    {
                        
                        string imageUri = callback.Data.Head.Substring(0, callback.Data.Head.Length - 2);
                        //Stream stream = App.GetResourceStream(new Uri(imageUri + "/100", UriKind.Absolute)).Stream;
                        ImageSource source = new BitmapImage(new Uri(imageUri + "/100", UriKind.Absolute));
                        //BitmapImage bitMap = new BitmapImage();
                        //bitMap.SetSource(stream);
                        DetailUserHead.Source = source;
                    }
                    if (callback.Data.Isvip == 1)
                    {
                        DetailUserVip.Visibility = Visibility.Visible;
                    }
                    DetailUserInfo.Tag = callback.Data.Name;
                    DetailProgressBar.IsIndeterminate = false;
                });
            });
        }

        /// <summary>
        /// 用于得到指定的评论列表
        /// </summary>
        private void RefreshCommentsList(PageFlag flag, long pagetime)
        {
            DetailProgressBar.IsIndeterminate = true;
            isPolling = true;
            lastPollTime = DateTime.Now;
            wcModel.getCommentList(weiboId, (int)flag, 10, pagetime, (callback) =>
            {
                isPolling = false;

                var newData = new List<Status>();
                callback.Data.ForEach(a =>
                {
                    DateTime date = new DateTime(1970, 01, 01, 00, 00, 00);
                    date = date.AddSeconds(a.Timestamp);
                    a.From = date.Month + "月" + date.Day + "日 " + date.Hour + ":" + date.Minute + "  " + a.From;
                    if (null == a.Head || a.Head.Equals(""))
                    {
                        a.Head = "Resources/head_50.jpg";
                    }
                    newData.Add(a);
                    //}
                });

                var data = (IEnumerable<Status>)DetailCommentsList.ItemsSource;

                if (pollType == EPollType.NextPage)
                {
                    data = data.Concat(newData).ToList();
                    //data = newData.Concat(data).ToList();
                }
                else if (pollType == EPollType.Lastest)
                {
                    newData = newData.Where(t => t.Timestamp > firstTimestamp).ToList();
                    if (newData.Count > 0)
                    {
                        data = newData.Concat(data).ToList();
                        //data = data.Concat(newData).ToList();
                    }
                }
                else
                {
                    data = newData;
                }

                if (data != null && data.Count() > 0)
                {
                    lastTimestamp = data.LastOrDefault().Timestamp;

                    firstTimestamp = data.FirstOrDefault().Timestamp;
                }

                DetailCommentsList.ItemsSource = data;
                DetailCommentsList.UpdateLayout();

                // 对数据进行处理

                Dispatcher.BeginInvoke(() =>
                {
                    DetailProgressBar.IsIndeterminate = false;
                });
            });
        }

        /// <summary>
        /// 页面切换改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DetailPanorama.SelectedIndex == 0)
            {
                if (null == DetailItemGrid.DataContext)
                {
                    RefreshWeiboDetail();
                }
            }
            if (DetailPanorama.SelectedIndex == 1)
            {
                if (null == (IEnumerable<Status>)DetailCommentsList.ItemsSource)
                {
                    RefreshCommentsList(PageFlag.First, 0);
                }
            }
            //PanoramaItem item = (PanoramaItem)((Panorama)sender).SelectedItem;
            //if (item.Header.Equals("微博详情"))
            //{
            //    if (null == DetailItemGrid.DataContext)
            //    {
            //        RefreshWeiboDetail();
            //    }
            //}
            //if (item.Header.Equals("微博评论"))
            //{
            //    if (null == (IEnumerable<Status>)DetailCommentsList.ItemsSource)
            //    {
            //        RefreshCommentsList(PageFlag.First, 0);
            //    }
            //}
        }

        #endregion

        #region 点评列表事件处理

        /// <summary>
        /// listbox拖动开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            if (e.Direction.ToString().Equals("Vertical"))
            {
                isVerticalDrag = true;
            }
        }
        
        /// <summary>
        /// 手势完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            if (isVerticalDrag || AppSetting.HightDragSensitivity)
            {
                var scrollView = AppSetting.FindChildOfType<ScrollViewer>(DetailCommentsList);
                if (null == scrollView)
                {
                    return;
                }
                // 移动至底部
                if (Math.Abs(scrollView.VerticalOffset - scrollView.ScrollableHeight) < 2)
                {
                    pollType = EPollType.NextPage;
                    RefreshCommentsList(PageFlag.Down, lastTimestamp);
                }
                else if (scrollView.VerticalOffset < 0.000001)
                {
                    pollType = EPollType.Lastest;
                    RefreshCommentsList(PageFlag.First, firstTimestamp);
                }
            }
        }

        #endregion

        #region applicationbar的按钮事件处理

        /// <summary>
        /// 反复按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailBackBarBtn_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        /// <summary>
        /// 主页按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailHomeBarBtn_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// 转播按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RePostBarBtn_Click(object sender, EventArgs e)
        {
            Status status = (Status)DetailItemGrid.DataContext;
            if (null != status)
            {
                IsoSetting.Set(IsoHelper.FatherStatusKey, status);
                NavigationService.Navigate(new Uri(string.Format("/UserControler/AddStatus.xaml?{0}={1}", AppSetting.AddStatusTypeKey, (int)AddStatusType.ReAdd.GetHashCode()), UriKind.Relative));
            }
        }

        /// <summary>
        /// 评论按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailCommentBarBtn_Click(object sender, EventArgs e)
        {
            Status status = (Status)DetailItemGrid.DataContext;
            if (null != status)
            {
                IsoSetting.Set(IsoHelper.FatherStatusKey, status);
                NavigationService.Navigate(new Uri(string.Format("/UserControler/AddStatus.xaml?{0}={1}", AppSetting.AddStatusTypeKey, (int)AddStatusType.Reply.GetHashCode()), UriKind.Relative));
            }
        }

        /// <summary>
        /// 收藏按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailCollectBarBtn_Click(object sender, EventArgs e)
        {
            bool isAdd = true;
            wcModel.FavoriteWeibo(weiboId, isAdd, (callback) =>
            {
                if (callback.Data.Ret == 1)
                {
                    // 成功
                }
                else
                {
                    // 失败
                }
            });
        }

        /// <summary>
        /// 用户信息的TAP事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailUserInfo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            StackPanel panel = sender as StackPanel;
            if (null != panel)
            {
                string name = panel.Tag.ToString();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    NavigationService.Navigate(new Uri(string.Format("/UserControler/UserDetailView.xaml?{0}={1}", AppSetting.UserNameKey, name), UriKind.Relative));
                }
            }
        }

        #endregion

    }
}